package com.acme.bankapp.service.bank;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.acme.bankapp.domain.bank.AbstractAccount;
import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.domain.exceptions.ClientExistsException;

public class BankService {
		
	protected String loadFeed;
	protected String saveReadFile;
	protected boolean bankLoading = true;
	
	public BankService (String lf, String saveReadFile) {		
		loadFeed = lf;
		this.saveReadFile = saveReadFile;	
	}
	
	public void addClient(Bank bank, Client client) throws ClientExistsException, IOException {		
		bank.addClient(client);
		if(!bankLoading)
			saveBank(bank);
	}
	
	public void printMaximumAmountToWithdraw(Bank bank) {
		Set <Client> clients = bank.getClients();
		Iterator<Client> iter = clients.iterator();
		Map <Integer, AbstractAccount> clientAccounts;
		Collection<AbstractAccount> set;
		Iterator <AbstractAccount> accIter;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; iter.hasNext(); i++) {
			clientAccounts = iter.next().getAccounts();			
			sb.append("Maximum amount to withdraw for client " + i + " is ");
			set = clientAccounts.values();
			accIter = set.iterator();
			while (accIter.hasNext()) {
				sb.append(accIter.next().maximumAmountToWithdraw());
			}
		}		
	}
	
	public Bank readBank() throws ClassNotFoundException, IOException {
		FileInputStream fis = new FileInputStream(saveReadFile);
		ObjectInputStream ois = new ObjectInputStream(fis);
		
		if(bankLoading) { //cheking if we load bank for the first time
			bankLoading = false;
		}
		
		Bank b = (Bank) ois.readObject();
		ois.close();
		fis.close();
		return b;
	}
	
	
	public void saveBank(Bank bank) throws IOException {
		FileOutputStream fos = new FileOutputStream(saveReadFile);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(bank);
		oos.close();
		fos.close();		
	}
}
